﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using SD.Database.Classes;
using System.Collections.Generic;
using System.Text;
using DBAccess;

namespace SD.Database
{
    public partial class StoredProcedures
    {
        public static void UpdatePlanets()
        {

            Dictionary<string, double> commands = new Dictionary<string, double>();
            int intervalTime = int.Parse(Configuration.GetConfigurationForOption("SmallUpdateInterval"));//in seconds
            double growthBonus = double.Parse(Configuration.GetConfigurationForOption("GrowthBonus"));
            double prodBonus = double.Parse(Configuration.GetConfigurationForOption("ProductionBonus"));
            Dictionary<int, int> TABonus = Agreements.TABonuses();

            try
            {
                string cmd = @"SELECT     Planets.PlanetID, Planets.SystemID, Planets.OwnerID, Planets.FleetOwnerID, 
                      Planets.Farms, Planets.Factories, Planets.Cybernets, 
                      Planets.Labs, Planets.Starbase, Planets.PopulationLevel, Planets.PopToNextLevel, Planets.ProductionPoints, 
                      Players.Social, Players.ArtifactID, Players.Growth, Players.Production
                      FROM Planets INNER JOIN Players ON Planets.OwnerID = Players.PlayerId
                      WHERE (Planets.OwnerID > 1)";

                DataSet ds = DAL.GetInstance().GetData(cmd);

                if (ds.Tables.Count == 0) return;
                foreach (DataRow rdr in ds.Tables[0].Rows)
                {
                    int pId = int.Parse(rdr["PlanetID"].ToString());
                    int sId = int.Parse(rdr["SystemID"].ToString());
                    int owner = int.Parse(rdr["OwnerID"].ToString());
                    //update growth
                    int maxPop, currentPopulation, farms;
                    double popToNextLevel;
                    double bonus;
                    try
                    {
                        string aId = rdr["ArtifactID"] as string;
                        //update production
                        bonus = 1.0 + int.Parse(rdr["Production"].ToString()) * prodBonus + TABonus[owner] * 1.0 / 100.0;
                        if (aId != null)
                        {
                            switch (aId)
                            {
                                case "CS":
                                    bonus = bonus + 0.1; break;
                                case "RF":
                                    bonus = bonus + 0.2; break;
                                case "NF":
                                    bonus = bonus + 0.3; break;
                                case "STr":
                                    bonus = bonus - 0.15; break;
                                case "BHS":
                                    bonus = bonus - 0.1; break;
                                case "AF":
                                    bonus -= 0.5; break;
                            }
                        }
                        double planetProduction = 1 + (int)double.Parse(rdr["Factories"].ToString()) + int.Parse(rdr["PopulationLevel"].ToString());
                        double outpp = planetProduction * bonus;
                        if (outpp < 0)
                            outpp = 0.01;
                        DAL.GetInstance().UpdateData("Update Planets Set ProductionPoints = ProductionPoints + @param0 Where PlanetID = @param1 and SystemId = @param2", new List<object>() { outpp / (3600 / intervalTime), pId, sId });

                        //update population
                        maxPop = UserFunctions.MaxPopulationForPlanet((int)double.Parse(rdr["Social"].ToString()));
                        if (int.Parse(rdr["PopulationLevel"].ToString()) == maxPop)
                            continue;

                        popToNextLevel = double.Parse(rdr["PopToNextLevel"].ToString());
                        farms = 1 + (int)double.Parse(rdr["Farms"].ToString());
                        currentPopulation = int.Parse(rdr["PopulationLevel"].ToString());
                        //get growth bonus
                        bonus = 1.0 + int.Parse(rdr["Growth"].ToString()) * growthBonus + TABonus[owner] * 1.0 / 100.0;
                        //get artifact bonus

                        if (aId != null)
                        {
                            switch (aId)
                            {
                                case "E1":
                                    bonus = bonus + 0.1; break;
                                case "E2":
                                    bonus = bonus + 0.2; break;
                                case "E3":
                                    bonus = bonus + 0.3; break;
                                case "STr":
                                    bonus = bonus + 0.2; break;
                                case "BHS":
                                    bonus = bonus - 0.1; break;
                                case "AF":
                                    bonus -= 0.9; break;
                                case "MOT": bonus += 0.2; break;
                            }
                        }

                        double output = farms * 1.0 * bonus;
                        if (output < 0)
                            output = 0.01;
                        
                        //InsertLog(DateTime.Now, "UpdatePlanets", "Updating planet: " + pId + " " + sId);
                        if (popToNextLevel * 1.0 - output / (3600.0 / intervalTime) <= 0) // add a pop
                        {
                            DAL.GetInstance().UpdateData("UPdate planets Set PopulationLevel = @param0, PopToNextLevel = @param1 Where PlanetID = @param2 and SystemId = @param3", new List<object>() { (currentPopulation + 1), Equations.PopulationLevel(currentPopulation + 1), pId, sId });
                        }
                        else
                        {
                            DAL.GetInstance().UpdateData("UPdate planets Set  PopToNextLevel = PopToNextLevel - @param0 Where PlanetID = @param1 and SystemId = @param2", new List<object>() { farms * 1.0 * bonus / (3600.0 / intervalTime), pId, sId });
                        }

                    }
                    catch (Exception ex)
                    {
                        InsertLog(DateTime.Now, "UpdatePlanets", ex.ToString());
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                InsertLog(DateTime.Now, "Update planets", ex.ToString());
            }
        }
    };
}